/**
 * 
 */
package com.redoor.iot.security.rbac;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.redoor.iot.security.MyUser;

/**
 * @author Administrator
 *
 */
@Service("rbacService")
public class RbacServiceImpl implements RbacService {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	private AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@Override
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) throws JsonParseException, JsonMappingException, IOException {
		boolean hasPermission = false;
		Object principal = authentication.getPrincipal();
		String username = null;
		if(principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		}
		if(StringUtils.isEmpty(username)) {
			return hasPermission;
		}
		
		String requestURI = request.getRequestURI();
		logger.info("requestURI={}",requestURI);
		
		//资源表中添加新的url之后，要退出重新登录url资源才会生效
        MyUser myPrincipal = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> passUrls = myPrincipal.getPassUrls();
		for(String url : passUrls) {
			if(StringUtils.isNoneBlank(url)) {
				logger.info("循环url={}",url);
				if(antPathMatcher.match(url, requestURI)) {
					hasPermission = true ;
					break;
				}
			}
		}
		return hasPermission;
	}

}
